<!--
* @FileDescription: 历史曲线页面
* @Author: yuec621@outlook.com
* @Date: 2024-11-5 12:43:55
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2025-05-15 09:29:02
-->
<template>
  <div class="pagestyle">
    <noDataChartCom v-if="state.nodataShow" @toolChange="toolChange" :searListData="state.searList"
      :lineConParams="state.lineConParams" @radioChange="radioChange" :attrObj="state.attrObj"></noDataChartCom>
    <div v-else>
      <div class="cardBox" :style="{
          backgroundColor:
            state.attrObj && state.attrObj.chartBg
              ? state.attrObj.chartBg
              : '#fff',
        }">
        <toolCom @toolChange="toolChange" :showToolList="state.showToolList" :lineConParams="state.lineConParams"
          :searList="state.searList" :totaltoolList="state.totaltoolList" :chartType="1" 
          :timeRange="state.timeRange"
          :lengedList="state.lengedList" @radioChange="radioChange" :attrObj="state.attrObj">
          <template v-slot:toolComTitle> 曲线配置 </template>
        </toolCom>
        <div v-loading="state.loading">
          <chartCom ref="chartRef" :chartList="state.chartList" :symbolShow="state.symbolShow"
            :alarmList="state.alarmList" :splitNumber="state.splitNumber" :toolType="state.toolType"
            :attrObj="state.attrObj" @toolChange="toolChange" :maxMinScale="state.maxMinScale"
            :selfAdaption="state.selfAdaption" :timeRange="state.timeRange"></chartCom>
        </div>
        <ganteCom @ganteChange="ganteChangere" :ganteList="state.ganteList" :timeRange="state.timeRange"></ganteCom>
      </div>
      <div class="cardBox">
        <chartTable :curdShow="true" :tableheadsValue="state.tableheadsValue" :tabledata="state.tabledata"
          :listSS="state.listSS">
          <template v-slot:tabBoxList="row">
            <span class="hover" v-for="item in state.tabList" :class="item.type == state.type ? 'bg' : ''"
              @click="tabClick(item)">
              {{ item.name }}({{ item.num }})</span>
          </template>
          <template v-slot:listSS="{ row, field }">
            <span v-if="field == 'alarmStartValue'" style="
                color: rgba(255, 85, 85, 1);
                font-size: 16px;
                font-weight: 700;
              ">
              {{ row.alarmStartValue }}
            </span>
            <span v-if="field == 'cutStartValue'" style="
                color: rgba(255, 85, 85, 1);
                font-size: 16px;
                font-weight: 700;
              ">
              {{ row.cutStartValue }}
            </span>
          </template>
          <template v-slot:opraCurdBtn="row">
            <el-button type="text" @click="lookLineClick(row.row)">查看曲线</el-button>
          </template>
        </chartTable>
      </div>
    </div>
  </div>
</template>
<script setup>
  import toolCom from "./chartCom/toolCom.vue";
  import chartCom from "./chartCom/chartCom.vue";
  import ganteCom from "./chartCom/ganteCom.vue";
  import chartTable from "./chartCom/chartTable.vue";
  import noDataChartCom from "./chartCom/noDataChartCom.vue";
  import {
    computed,
    nextTick,
    onMounted,
    reactive
  } from "vue";
  import {
    table_headers
  } from "@/components/commonCom/table_headers";
  import axios from "@/utils/request";
  import usePagesStore from "@/store/modules/pages";
  import dayjs from "dayjs";
  const {
    proxy
  } = getCurrentInstance();
  const store = usePagesStore();
  const router = useRouter();
  let previewHttps =
    import.meta.env.VITE_APP_HTTP;
  const chartRef = ref(null);
  let state = reactive({
     loading:false,
    nodataShow: false,
    toolType: null,
    tabledata: [],
    timeRange: [],
    chartList: {},
    ganteList: [],
    symbolShow: false,
    chartLength: 0,
    alarmList: {},
    showToolList: false, //查看曲线展示前一条后一条
    splitNumber: 10,
    tableheadsValue: computed(() => table_headers.hisAlarmLineTable),
    listSS: [{
        field: "alarmStartValue",
      },
      {
        field: "cutStartValue",
      },
    ],
    options: {
      tableheads: computed(() => table_headers.hisAlarmLineTable),
      tableheadstwo: computed(() => table_headers.hisCutLineTable),
      tableheadsthr: computed(() => table_headers.hisFeedLineTable),
      queryList: {
        dropdownUrl: "",
        querys: [{
          field: "pointName",
          title: "传感器名称",
          type: "input",
          binddata: "",
        }, ],
        queryMap: new Map([
          ["sensorTypeId", "safety_pointType"],
          ["deviceTypeId", "safety_deviceType"],
          ["alarmTypeId", "alarmType"],
        ]),
      },
      dataUrl: "/constant/list",
      delUrl: "/constant/del",
      addUrl: "/constant/add",
      descUrl: "/constant/getById",
      editUrl: "/constant/modify",
    },
    tabList: [{
        type: 0,
        name: "报警",
        num: 0,
        tableheads: computed(() => table_headers.hisAlarmLineTable),
        dataUrl: "/pointData/hisAlarmTable",
        tableData: [],
      },
      {
        type: 1,
        name: "断电",
        num: 0,
        tableheads: computed(() => table_headers.hisCutLineTable),
        dataUrl: "/pointData/hisCutTable",
        tableData: [],
      },
      {
        type: 2,
        name: "馈电异常",
        num: 0,
        tableheads: computed(() => table_headers.hisFeedLineTable),
        dataUrl: "/pointData/hisFeedTable",
        tableData: [],
      },
    ],
    type: 0,
    lineConParams: {
      type: 'A',
      pointUrl: "/simulate/history/attainPoints", //获取测点列表
      addTemSave: "/simulate/template/add", //新增模板接口
      tempList: "/simulate/template/list", //模板列表接口
      delTemp: "/simulate/template/del", //删除模板接口
      hisSearchSave: "/simulate/history/add", //新增历史查询接口
      hisSearchList: "/simulate/history/list", //查询历史查询接口
      hisSearchDel: "/simulate/history/del", //删除历史查询接口
      gethisAlarmScale: '/pointData/hisAlarmScale', //报警范围
      gethisCutScale: '/pointData/hisCutScale', //断电范围
      gethisFeedScale: '/pointData/hisFeedScale', //馈电范围
    },
    pointIdList: [],
    searList: [{
        label: "时间范围",
        id: "time",
        descList: [{
          label: "时间范围",
          type: "timeRangepage",
          col: 24,
          bindData: undefined,
          field: "timeRange"
        }],
      },
      {
        label: "测点信息",
        id: "pointLocal",
        descList: [{
            label: '传感器精度',
            type: 'radio',
            col: 24,
            bindData: false,
            field: undefined,
            judcond: 'jingdu', //判断条件
            options: [{
              label: '自适应',
              value: false
            }, {
              label: '量程',
              value: true
            }],
          },
          {
            label: "传感器分类",
            type: "select",
            col: 24,
            bindData: false,
            iSdefault: true,
            judcond: 'deviceCate', //判断条件
            field: "flag",
            options: [{
                label: "显示设备名称",
                value: false,
              },
              {
                label: "瓦斯抽采点",
                value: true,
              },
            ],
          },
          {
            label: "传感器名称",
            type: "select",
            col: 24,
            bindData: undefined,
            options: [],
            judcond: 'sensorchoiceName', //判断条件
            field: 'choiceName',
            fieldT: 'sensorName'
          },
        ],
      },
      {
        label: "地点区域",
        id: "area",
        descList: [{
            label: "所在区域",
            type: "cascadercheckStrictly",
            col: 24,
            bindData: undefined,
            options: [],
            field: 'areaId',
            fieldT: 'areaName',
            judcond: 'areaName', //判断条件
            props: {
              children: "childList",
              value: "id",
              label: "areaName",
              checkStrictly: true,
              emitPath: false,
            },
          },
          {
            label: "安装地点",
            type: "select",
            col: 24,
            bindData: undefined,
            options: [],
            field: "placeName",
            judcond: 'placeName', //判断条件
          },
        ],
      },
    ],
    attrList: [],
    attrObj: undefined,
    totaltoolList: [{
        name: "今",
        icon: "jintian",
        type: 0,
        selname: "取消今日",
        show: true,
      },
      {
        name: "前一天",
        icon: "qianyitian",
        type: 1,
        selname: "取消前一天",
        show: true,
      },
      {
        name: "后一天",
        icon: "houyitian",
        type: 2,
        selname: "取消后一天",
        show: true,
      },
      {
        name: "事件日历",
        icon: "rilishijian",
        type: 3,
        selname: "取消事件日历",
        show: true,
      },
      {
        name: "显示圆点",
        icon: "yuandian",
        type: 4,
        selname: "取消显示圆点",
        show: true,
      },
      {
        name: "标尺",
        icon: "biaochi",
        type: 5,
        selname: "取消标尺",
        show: true,
      },
      {
        name: "游标",
        icon: "youbiao",
        type: 6,
        selname: "取消游标",
        show: true,
      },
      {
        name: "框选",
        icon: "kuangxuan",
        type: 7,
        selname: "取消框选",
        show: true,
      },
      {
        name: "纵向放大",
        icon: "zongxiangfangda",
        type: 10,
        selname: "取消纵向放大",
        show: true,
      },
    ],
    lengedList: [],
    /* 量程和自适应相关参数 */
    selfAdaption: false,
    maxMinScale: {
      upperRestriction: undefined,
      lowerRestriction: undefined
    },
  });
  // 传感器精度
  function radioChange(val, data) {
    if (data.judcond == 'jingdu') {
      state.selfAdaption = val
    }
  }

  function ganteChangere(startTime, endTime) {
    startTime = dayjs(startTime).format("YYYY-MM-DD HH:mm:ss");
    endTime = dayjs(endTime).format("YYYY-MM-DD HH:mm:ss");
    if (state.pointIdList.length > 0) {
      getList(startTime, endTime);
    }
  }
  // 获取曲线图数据
  function getList(startTime, endTime) {
    state.loading=true
    axios
      .post("/pointData/simulateLine", {
        pointIds: state.pointIdList,
        queryStartTime: startTime,
        queryEndTime: endTime,
      })
      .then((res) => {
        if (res.data.hisSimulateLines.length > 0) {
          res.data.hisSimulateLines.forEach((item) => {
            state.attrList.forEach((itemsub) => {
              if (item.pointId == itemsub.pointId) {
                item.attrObj = itemsub;
              }
            });
          });
        }
        state.chartList = res.data;
        state.loading=false
      });
  }
  // 获取报警虚线数据
  function getalarmList(startTime, endTime) {
    axios
      .post("/pointData/hisAlarmLine", {
        pointIds: state.pointIdList,
        queryStartTime: startTime,
        queryEndTime: endTime,
      })
      .then((res) => {
        state.alarmList = res.data;
      });
  }
  // 头部操作工具栏事件
  async function toolChange(val) {
    state.toolType = val.type;
    if (val.type == "dateType") {
      if (val.data && val.data.length > 0) {
        let startTime = dayjs(val.data[0]).format("YYYY-MM-DD HH:mm:ss");
        let endTime = dayjs(val.data[1]).format("YYYY-MM-DD HH:mm:ss");
        state.timeRange = [startTime, endTime];
        if (state.pointIdList.length > 0) {
          localStorage.setItem(
            "hisChart",
            JSON.stringify({
              pointIds: state.pointIdList,
              startTime: startTime,
              endTime: endTime,
              lengedList: state.lengedList,
              attrObj: state.attrObj
            })
          );
          await getList(startTime, endTime);
          await ganteList(startTime, endTime);
          await getalarmList(startTime, endTime);
          await tableList(startTime, endTime);
          if (state.selfAdaption) {
            await getMaxMinScale()
          }
          if (val.brushValue) {
            state.toolType = val.brushValue;
          }
        } else {
          proxy.$modal.msgWarning("请选择所要查询的测点编号!");
        }
      } else {
        proxy.$modal.msgWarning("请选择所要查询时间范围!");
      }
    } else if (val.type == "4") {
      state.symbolShow = val.data;
    } else if (val.type == "5") {
      state.toolType = val.data;
    } else if (val.type == "6") {
      state.toolType = val.data;
    } else if (val.type == "7") {
      state.toolType = val.data;
    } else if (val.type == "8") {
      state.chartLength = state.chartList.length;
      state.chartList[0].hisSimulateLines.forEach((item, index) => {});
    } else if (val.type == "10") {
      state.splitNumber -= 1;
      if (state.splitNumber < 1) {
        state.splitNumber -= 0.1;
        if (state.splitNumber < 0.1) {
          state.splitNumber = 10;
        }
      }
    } else if (val.type == "12") {
      state.toolType = val.type;
    } else if (val.type == "legend") {
      state.lengedList = val.data;
      state.attrObj = val.attrObj;
      state.attrList = val.data;
      state.pointIdList = val.data.map((item) => {
        return item.pointId;
      });
    } else if (val.type == "checkedlegend") {
      if (val.data.valueType) {
        for (var i = 0; i < state.chartList.hisSimulateLines.length; i++) {
          state.chartList.hisSimulateLines[i].maxShow = true;
          val.data.data.forEach((itemmax) => {
            if (itemmax.type == "max") {
              state.chartList.hisSimulateLines[i].opacitymax = itemmax.valueType ?
                0.2 :
                1;
            }
            if (itemmax.type == "min") {
              state.chartList.hisSimulateLines[i].opacitymin = itemmax.valueType ?
                0.2 :
                1;
            }
            if (itemmax.type == "avg") {
              state.chartList.hisSimulateLines[i].opacityavg = itemmax.valueType ?
                0.2 :
                1;
            }
          });
        }
      } else {
        var valList = val.data.map((item) => {
          return item.pointId;
        });
        for (var i = 0; i < state.chartList.hisSimulateLines.length; i++) {
          //不存在则返回-1
          if (
            valList.indexOf(state.chartList.hisSimulateLines[i].pointId) === -1
          ) {
            state.chartList.hisSimulateLines[i].maxShow = false;
            state.chartList.hisSimulateLines[i].opacity = 0.2;
          } else {
            state.chartList.hisSimulateLines[i].maxShow = false;
            state.chartList.hisSimulateLines[i].opacity = 1;
          }
        }
      }
    } else if (val.type == "legendshow") {
      state.lengedList = val.data;
      // state.attrObj = val.attrObj;
      state.attrList = val.data;
      state.pointIdList = val.data.map((item) => {
        return item.pointId;
      });
      state.nodataShow = false;
    } else if (val.type == "13") {
      state.toolType = val.type;
    }
  }
  // 获取甘特图数据
  function ganteList(startTime, endTime) {
    axios
      .post("/pointData/simulateError", {
        pointIds: state.pointIdList,
        queryStartTime: startTime,
        queryEndTime: endTime,
      })
      .then((res) => {
        if (res.code == 200) {
          let arrnew = [];
          res.data.forEach((item) => {
            let errorTypesvalue = item.errorTypes.map((itemsub) => {
              return {
                typeValue: itemsub,
                errorStartTime: item.errorStartTime,
                errorEndTime: item.errorEndTime,
              };
            });
            arrnew.push(...errorTypesvalue);
            state.ganteList = arrnew;
          });
        }
      });
  }
  // 查看曲线按钮
  function lookLineClick(row) {
    if (state.type == 0) {
      router.push({
        path: "/qx/qx_alarmChart",
        query: {
          pointIds: row.pointId,
          startTime: row.alarmStartTime,
          endTime: row.alarmEndTime,
        },
      });
    } else if (state.type == 1) {
      router.push({
        path: "/qx/qx_cutChart",
        query: {
          pointIds: row.pointId,
          startTime: row.cutStartTime,
          endTime: row.cutEndTime,
        },
      });
    } else {
      router.push({
        path: "/qx/qx_kuidianChart",
        query: {
          pointIds: row.pointId,
          startTime: row.feedStartTime,
          endTime: row.feedEndTime,
        },
      });
    }
    state.showToolList = true;
  }
  // 获取表格数据
  function tableList(startTime, endTime) {
    let data = {
      pointIds: state.pointIdList,
      queryStartTime: startTime,
      queryEndTime: endTime,
    };
    state.tabList.forEach((item, index) => {
      axios.post(item.dataUrl, data).then((res) => {
        if (index == 0) {
          state.tabledata = res.data.list;
        }
        item.tableData = res.data.list;
        item.num = res.data.list.length;
      });
    });
    state.tabledata = state.tabList[0].tableData;
  }
  // 获取纵坐标最大最小范围接口
  function getMaxMinScale() {
    let data = {
      pointIds: state.pointIdList,
      queryStartTime: state.timeRange[0],
      queryEndTime: state.timeRange[1],
      selfAdaption: state.selfAdaption
    }
    axios.post(state.type == 0 ? state.lineConParams.gethisAlarmScale : state.type == 1 ? state.lineConParams
      .gethisCutScale : state.lineConParams.gethisFeedScale, data).then(res => {
      state.maxMinScale = res.data
    })
  }
  // 列表tab切换
  function tabClick(item) {
    state.tabledata = item.tableData;
    state.type = item.type;
    if (state.selfAdaption) {
      getMaxMinScale()
    }
    if (item.type == 0) {
      setTimeout(() => {
        state.tableheadsValue = computed(() => table_headers.hisAlarmLineTable);
      }, 300);
    } else if (item.type == 1) {
      setTimeout(() => {
        state.tableheadsValue = computed(() => table_headers.hisCutLineTable);
      }, 300);
    } else {
      setTimeout(() => {
        state.tableheadsValue = computed(() => table_headers.hisFeedLineTable);
      }, 300);
    }
  }
  const props = defineProps({
    fromIndexpointId: Object
  })
  onMounted(() => {
    // localStorage.removeItem('hisChart')
    let hisChartStore = JSON.parse(localStorage.getItem("hisChart"));
    if (hisChartStore != null) {
      state.nodataShow = false;
      state.pointIdList = hisChartStore.lengedList.map((item) => {
        return item.pointId;
      });
      if (hisChartStore.attrObj) {
        state.attrObj = hisChartStore.attrObj
      }
      state.lengedList = hisChartStore.lengedList;
      state.timeRange = [hisChartStore.startTime, hisChartStore.endTime];
      getList(hisChartStore.startTime, hisChartStore.endTime);
      ganteList(hisChartStore.startTime, hisChartStore.endTime);
      getalarmList(hisChartStore.startTime, hisChartStore.endTime);
      tableList(hisChartStore.startTime, hisChartStore.endTime);
      if (state.selfAdaption) {
        getMaxMinScale()
      }
    } else {
      if (props.fromIndexpointId) {
        state.nodataShow = false
        state.pointIdList = [props.fromIndexpointId.pointId]
        state.timeRange = [dayjs().format('YYYY-MM-DD 00:00:00'), dayjs().format('YYYY-MM-DD hh:mm:ss')]
        getList(state.timeRange[0], state.timeRange[1]);
        ganteList(state.timeRange[0], state.timeRange[1]);
        getalarmList(state.timeRange[0], state.timeRange[1]);
        tableList(state.timeRange[0], state.timeRange[1]);

        if (state.selfAdaption) {
          getMaxMinScale()
        }
      } else {
        state.nodataShow = true
      }
    }
  });
</script>
<style lang="scss" scoped>
  .pagestyle {
    overflow-y: auto;

    .cardBox {
      padding: 10px;
      margin: 10px;
      border-radius: 8px;
      margin-top: 10px;
      background-color: rgba($color: #ffffff, $alpha: 0.6);
    }
  }
</style>